github.com/micro/go-micro/v2@v2.9.1/util/http/http.go (about)

     1  package http
     2  
     3  import (
     4  	"context"
     5  	"encoding/json"
     6  	"fmt"
     7  	"log"
     8  	"net/http"
     9  	"strings"
    10  
    11  	"github.com/micro/go-micro/v2/client/selector"
    12  	"github.com/micro/go-micro/v2/metadata"
    13  	"github.com/micro/go-micro/v2/registry"
    14  )
    15  
    16  // Write sets the status and body on a http ResponseWriter
    17  func Write(w http.ResponseWriter, contentType string, status int, body string) {
    18  	w.Header().Set("Content-Length", fmt.Sprintf("%v", len(body)))
    19  	w.Header().Set("Content-Type", contentType)
    20  	w.WriteHeader(status)
    21  	fmt.Fprintf(w, `%v`, body)
    22  }
    23  
    24  // WriteBadRequestError sets a 400 status code
    25  func WriteBadRequestError(w http.ResponseWriter, err error) {
    26  	rawBody, err := json.Marshal(map[string]string{
    27  		"error": err.Error(),
    28  	})
    29  	if err != nil {
    30  		WriteInternalServerError(w, err)
    31  		return
    32  	}
    33  	Write(w, "application/json", 400, string(rawBody))
    34  }
    35  
    36  // WriteInternalServerError sets a 500 status code
    37  func WriteInternalServerError(w http.ResponseWriter, err error) {
    38  	rawBody, err := json.Marshal(map[string]string{
    39  		"error": err.Error(),
    40  	})
    41  	if err != nil {
    42  		log.Println(err)
    43  		return
    44  	}
    45  	Write(w, "application/json", 500, string(rawBody))
    46  }
    47  
    48  func NewRoundTripper(opts ...Option) http.RoundTripper {
    49  	options := Options{
    50  		Registry: registry.DefaultRegistry,
    51  	}
    52  	for _, o := range opts {
    53  		o(&options)
    54  	}
    55  
    56  	return &roundTripper{
    57  		rt:   http.DefaultTransport,
    58  		st:   selector.Random,
    59  		opts: options,
    60  	}
    61  }
    62  
    63  // RequestToContext puts the `Authorization` header bearer token into context
    64  // so calls to services will be authorized.
    65  func RequestToContext(r *http.Request) context.Context {
    66  	ctx := context.Background()
    67  	md := make(metadata.Metadata)
    68  	for k, v := range r.Header {
    69  		md[k] = strings.Join(v, ",")
    70  	}
    71  	return metadata.NewContext(ctx, md)
    72  }