github.com/GoogleCloudPlatform/testgrid@v0.0.174/pkg/api/v1/json.go (about)

     1  /*
     2  Copyright 2021 The TestGrid Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package v1
    18  
    19  import (
    20  	"net/http"
    21  
    22  	"google.golang.org/protobuf/encoding/protojson"
    23  	"google.golang.org/protobuf/proto"
    24  )
    25  
    26  // writeJSON will write obj to w as JSON, or will write the JSON marshalling error
    27  // Includes headers that are universal to all API responses
    28  func (s Server) writeJSON(w http.ResponseWriter, msg proto.Message) {
    29  
    30  	opts := protojson.MarshalOptions{UseProtoNames: true}
    31  	resp, err := opts.Marshal(msg)
    32  	if err != nil {
    33  		http.Error(w, err.Error(), http.StatusInternalServerError)
    34  		return
    35  	}
    36  
    37  	w.Header().Set("Content-Type", "application/json")
    38  	if s.AccessControlAllowOrigin != "" {
    39  		w.Header().Set("Access-Control-Allow-Origin", s.AccessControlAllowOrigin)
    40  		if s.AccessControlAllowOrigin != "*" {
    41  			w.Header().Set("Vary", "Origin")
    42  		}
    43  	}
    44  	w.Write(resp)
    45  }