github.com/xushiwei/go@v0.0.0-20130601165731-2b9d83f45bc9/src/cmd/godoc/play.go (about)

     1  // Copyright 2012 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Common Playground functionality.
     6  
     7  package main
     8  
     9  import (
    10  	"encoding/json"
    11  	"fmt"
    12  	"go/format"
    13  	"net/http"
    14  )
    15  
    16  // The server that will service compile and share requests.
    17  const playgroundBaseURL = "http://play.golang.org"
    18  
    19  func registerPlaygroundHandlers(mux *http.ServeMux) {
    20  	if *showPlayground {
    21  		mux.HandleFunc("/compile", bounceToPlayground)
    22  		mux.HandleFunc("/share", bounceToPlayground)
    23  	} else {
    24  		mux.HandleFunc("/compile", disabledHandler)
    25  		mux.HandleFunc("/share", disabledHandler)
    26  	}
    27  	http.HandleFunc("/fmt", fmtHandler)
    28  }
    29  
    30  type fmtResponse struct {
    31  	Body  string
    32  	Error string
    33  }
    34  
    35  // fmtHandler takes a Go program in its "body" form value, formats it with
    36  // standard gofmt formatting, and writes a fmtResponse as a JSON object.
    37  func fmtHandler(w http.ResponseWriter, r *http.Request) {
    38  	resp := new(fmtResponse)
    39  	body, err := format.Source([]byte(r.FormValue("body")))
    40  	if err != nil {
    41  		resp.Error = err.Error()
    42  	} else {
    43  		resp.Body = string(body)
    44  	}
    45  	json.NewEncoder(w).Encode(resp)
    46  }
    47  
    48  // disabledHandler serves a 501 "Not Implemented" response.
    49  func disabledHandler(w http.ResponseWriter, r *http.Request) {
    50  	w.WriteHeader(http.StatusNotImplemented)
    51  	fmt.Fprint(w, "This functionality is not available via local godoc.")
    52  }