github.com/hechain20/hechain@v0.0.0-20220316014945-b544036ba106/internal/osnadmin/join.go (about)

     1  /*
     2  Copyright hechain. All Rights Reserved.
     3  
     4  SPDX-License-Identifier: Apache-2.0
     5  */
     6  
     7  package osnadmin
     8  
     9  import (
    10  	"bytes"
    11  	"crypto/tls"
    12  	"crypto/x509"
    13  	"fmt"
    14  	"mime/multipart"
    15  	"net/http"
    16  )
    17  
    18  // Joins an OSN to a new or existing channel.
    19  func Join(osnURL string, blockBytes []byte, caCertPool *x509.CertPool, tlsClientCert tls.Certificate) (*http.Response, error) {
    20  	url := fmt.Sprintf("%s/participation/v1/channels", osnURL)
    21  	req, err := createJoinRequest(url, blockBytes)
    22  	if err != nil {
    23  		return nil, err
    24  	}
    25  
    26  	return httpDo(req, caCertPool, tlsClientCert)
    27  }
    28  
    29  func createJoinRequest(url string, blockBytes []byte) (*http.Request, error) {
    30  	joinBody := new(bytes.Buffer)
    31  	writer := multipart.NewWriter(joinBody)
    32  	part, err := writer.CreateFormFile("config-block", "config.block")
    33  	if err != nil {
    34  		return nil, err
    35  	}
    36  	part.Write(blockBytes)
    37  	err = writer.Close()
    38  	if err != nil {
    39  		return nil, err
    40  	}
    41  
    42  	req, err := http.NewRequest(http.MethodPost, url, joinBody)
    43  	if err != nil {
    44  		return nil, err
    45  	}
    46  	req.Header.Set("Content-Type", writer.FormDataContentType())
    47  
    48  	return req, nil
    49  }