25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

92 lines
2.1 KiB

  1. // Copyright 2013 The Go Authors. All rights reserved.
  2. //
  3. // Use of this source code is governed by a BSD-style
  4. // license that can be found in the LICENSE file or at
  5. // https://developers.google.com/open-source/licenses/bsd.
  6. package main
  7. import (
  8. "fmt"
  9. "io/ioutil"
  10. "net/http"
  11. "regexp"
  12. "strings"
  13. "github.com/golang/gddo/doc"
  14. )
  15. func findExamples(pdoc *doc.Package, export, method string) []*doc.Example {
  16. if "package" == export {
  17. return pdoc.Examples
  18. }
  19. for _, f := range pdoc.Funcs {
  20. if f.Name == export {
  21. return f.Examples
  22. }
  23. }
  24. for _, t := range pdoc.Types {
  25. for _, f := range t.Funcs {
  26. if f.Name == export {
  27. return f.Examples
  28. }
  29. }
  30. if t.Name == export {
  31. if method == "" {
  32. return t.Examples
  33. }
  34. for _, m := range t.Methods {
  35. if method == m.Name {
  36. return m.Examples
  37. }
  38. }
  39. return nil
  40. }
  41. }
  42. return nil
  43. }
  44. func findExample(pdoc *doc.Package, export, method, name string) *doc.Example {
  45. for _, e := range findExamples(pdoc, export, method) {
  46. if name == e.Name {
  47. return e
  48. }
  49. }
  50. return nil
  51. }
  52. var exampleIDPat = regexp.MustCompile(`([^-]+)(?:-([^-]*)(?:-(.*))?)?`)
  53. func playURL(pdoc *doc.Package, id, countryHeader string) (string, error) {
  54. if m := exampleIDPat.FindStringSubmatch(id); m != nil {
  55. if e := findExample(pdoc, m[1], m[2], m[3]); e != nil && e.Play != "" {
  56. req, err := http.NewRequest("POST", "https://play.golang.org/share", strings.NewReader(e.Play))
  57. if err != nil {
  58. return "", err
  59. }
  60. req.Header.Set("Content-Type", "text/plain")
  61. if countryHeader != "" {
  62. // Forward the App Engine country header.
  63. req.Header.Set("X-AppEngine-Country", countryHeader)
  64. }
  65. resp, err := httpClient.Do(req)
  66. if err != nil {
  67. return "", err
  68. }
  69. defer resp.Body.Close()
  70. p, err := ioutil.ReadAll(resp.Body)
  71. if err != nil {
  72. return "", err
  73. }
  74. if resp.StatusCode > 399 {
  75. return "", &httpError{
  76. status: resp.StatusCode,
  77. err: fmt.Errorf("Error from play.golang.org: %s", p),
  78. }
  79. }
  80. return fmt.Sprintf("http://play.golang.org/p/%s", p), nil
  81. }
  82. }
  83. return "", &httpError{status: http.StatusNotFound}
  84. }