github.com/GuanceCloud/cliutils@v1.1.21/network/http/http_test.go (about)

     1  // Unless explicitly stated otherwise all files in this repository are licensed
     2  // under the MIT License.
     3  // This product includes software developed at Guance Cloud (https://www.guance.com/).
     4  // Copyright 2021-present Guance, Inc.
     5  
     6  package http
     7  
     8  import (
     9  
    10  	// nolint:gosec
    11  	"crypto/md5"
    12  	"fmt"
    13  	"log"
    14  	"net/http"
    15  	"testing"
    16  	"time"
    17  )
    18  
    19  func TestSign(t *testing.T) {
    20  	o := &SignOption{
    21  		AuthorizationType: "ABC",
    22  		SignHeaders:       []string{`Date`, `Content-MD5`, `Content-Type`},
    23  		SK:                "sk-cba",
    24  		AK:                "ak-123",
    25  		Sign:              "",
    26  	}
    27  
    28  	r, err := http.NewRequest(`POST`, `http://1.2.3.4:1234/v1/api`, http.NoBody)
    29  	if err != nil {
    30  		t.Fatal(err)
    31  	}
    32  
    33  	r.Header.Set("Date", time.Now().UTC().Format(http.TimeFormat))
    34  	r.Header.Set(`Content-MD5`, fmt.Sprintf("%x", md5.Sum([]byte(`{}`)))) //nolint:gosec
    35  	r.Header.Set(`Content-Type`, `application/json`)
    36  
    37  	o.Sign, err = o.SignReq(r)
    38  	if err != nil {
    39  		t.Fatal(err)
    40  	}
    41  
    42  	r.Header.Set(`Authorization`, fmt.Sprintf("%s %s:%s", o.AuthorizationType, o.AK, o.Sign))
    43  	log.Printf("[debug] %+#v", o)
    44  
    45  	o2 := &SignOption{
    46  		AuthorizationType: "ABC",
    47  		SignHeaders:       []string{`Date`, `Content-MD5`, `Content-Type`},
    48  		SK:                "sk-cba",
    49  		AK:                "ak-123",
    50  	}
    51  
    52  	if err := o2.ParseAuth(r); err != nil {
    53  		t.Fatal(err)
    54  	}
    55  
    56  	if sign, err := o2.SignReq(r); err != nil || o2.Sign != sign {
    57  		t.Fatalf("sign failed: %v, %s <> %s", err, o2.Sign, sign)
    58  	}
    59  	log.Printf("[debug] %+#v", o)
    60  }