github.com/micro/go-micro/examples@v0.0.0-20210105173217-bf4ab679e18b/api/proxy/proxy.go (about)

     1  package main
     2  
     3  import (
     4  	"encoding/json"
     5  	"log"
     6  	"net/http"
     7  
     8  	"github.com/micro/go-micro/v2/errors"
     9  	"github.com/micro/go-micro/v2/web"
    10  )
    11  
    12  // exampleCall will handle /example/call
    13  func exampleCall(w http.ResponseWriter, r *http.Request) {
    14  	r.ParseForm()
    15  	// get name
    16  	name := r.Form.Get("name")
    17  
    18  	if len(name) == 0 {
    19  		http.Error(
    20  			w,
    21  			errors.BadRequest("go.micro.api.example", "no content").Error(),
    22  			400,
    23  		)
    24  		return
    25  	}
    26  
    27  	// marshal response
    28  	b, _ := json.Marshal(map[string]interface{}{
    29  		"message": "got your message " + name,
    30  	})
    31  
    32  	// write response
    33  	w.Write(b)
    34  }
    35  
    36  // exampleFooBar will handle /example/foo/bar
    37  func exampleFooBar(w http.ResponseWriter, r *http.Request) {
    38  	if r.Method != "POST" {
    39  		http.Error(
    40  			w,
    41  			errors.BadRequest("go.micro.api.example", "require post").Error(),
    42  			400,
    43  		)
    44  		return
    45  	}
    46  
    47  	if len(r.Header.Get("Content-Type")) == 0 {
    48  		http.Error(
    49  			w,
    50  			errors.BadRequest("go.micro.api.example", "need content-type").Error(),
    51  			400,
    52  		)
    53  		return
    54  	}
    55  
    56  	if r.Header.Get("Content-Type") != "application/json" {
    57  		http.Error(
    58  			w,
    59  			errors.BadRequest("go.micro.api.example", "expect application/json").Error(),
    60  			400,
    61  		)
    62  		return
    63  	}
    64  
    65  	// do something
    66  }
    67  
    68  func main() {
    69  	// we're using go-web for convenience since it registers with discovery
    70  	service := web.NewService(
    71  		web.Name("go.micro.api.example"),
    72  	)
    73  
    74  	service.HandleFunc("/example/call", exampleCall)
    75  	service.HandleFunc("/example/foo/bar", exampleFooBar)
    76  
    77  	if err := service.Init(); err != nil {
    78  		log.Fatal(err)
    79  	}
    80  
    81  	if err := service.Run(); err != nil {
    82  		log.Fatal(err)
    83  	}
    84  }