首页 > 其他分享 >golang链式调用

golang链式调用

时间:2023-05-29 16:32:44浏览次数:37  
标签:body 调用 return err nil Request golang 链式 string

简单举例

package main

// 主要就是 前一个方法的返回值,具有下一个方法,因此可以实现链式调用

import "fmt"

type Stu struct {
	Name string
	Age  int
}

func (p *Stu) SetName(name string) *Stu {
	p.Name = name
	return p
}

func (p *Stu) SetAge(age int) *Stu {
	p.Age = age
	return p
}

func (p *Stu) Print() {
	fmt.Printf("age:%d, name:%s\n", p.Age, p.Name)
}

func main() {
	stu := &Stu{}
	stu.SetAge(12).SetName("baylor").Print() //这里就可以实现链式的调用
}

k8s源码

k8s源码示例代码位置:

golang链式调用_链式调用

/*
Copyright 2014 Google Inc. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package cloudcfg

import (
	"bytes"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"path"
	"time"

	"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/client"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/labels"
)

// Server contains info locating a kubernetes api server.
// Example usage:
// auth, err := LoadAuth(filename)
// s := New(url, auth)
// resp, err := s.Verb("GET").
//	Path("api/v1beta1").
//	Path("pods").
//	Selector("area=staging").
//	Timeout(10*time.Second).
//	Do()
// list, ok := resp.(api.PodList)
type Server struct {
	auth   *client.AuthInfo
	rawUrl string
}

// Create a new server object.
func New(serverUrl string, auth *client.AuthInfo) *Server {
	return &Server{
		auth:   auth,
		rawUrl: serverUrl,
	}
}

// Begin a request with a verb (GET, POST, PUT, DELETE)
func (s *Server) Verb(verb string) *Request {
	return &Request{
		verb: verb,
		s:    s,
		path: "/",
	}
}

// Request allows for building up a request to a server in a chained fashion.
type Request struct {
	s        *Server
	err      error
	verb     string
	path     string
	body     interface{}
	selector labels.Selector
	timeout  time.Duration
}

// Append an item to the request path. You must call Path at least once.
func (r *Request) Path(item string) *Request {
	if r.err != nil {
		return r
	}
	r.path = path.Join(r.path, item)
	return r
}

// Use the given item as a resource label selector. Optional.
func (r *Request) Selector(item string) *Request {
	if r.err != nil {
		return r
	}
	r.selector, r.err = labels.ParseSelector(item)
	return r
}

// Use the given duration as a timeout. Optional.
func (r *Request) Timeout(d time.Duration) *Request {
	if r.err != nil {
		return r
	}
	r.timeout = d
	return r
}

// Use obj as the body of the request. Optional.
// If obj is a string, try to read a file of that name.
// If obj is a []byte, send it directly.
// Otherwise, assume obj is an api type and marshall it correctly.
func (r *Request) Body(obj interface{}) *Request {
	if r.err != nil {
		return r
	}
	r.body = obj
	return r
}

// Format and xecute the request. Returns the API object received, or an error.
func (r *Request) Do() (interface{}, error) {
	if r.err != nil {
		return nil, r.err
	}
	finalUrl := r.s.rawUrl + r.path
	query := url.Values{}
	if r.selector != nil {
		query.Add("labels", r.selector.String())
	}
	if r.timeout != 0 {
		query.Add("timeout", r.timeout.String())
	}
	finalUrl += "?" + query.Encode()
	var body io.Reader
	if r.body != nil {
		switch t := r.body.(type) {
		case string:
			data, err := ioutil.ReadFile(t)
			if err != nil {
				return nil, err
			}
			body = bytes.NewBuffer(data)
		case []byte:
			body = bytes.NewBuffer(t)
		default:
			data, err := api.Encode(r.body)
			if err != nil {
				return nil, err
			}
			body = bytes.NewBuffer(data)
		}
	}
	req, err := http.NewRequest(r.verb, finalUrl, body)
	if err != nil {
		return nil, err
	}
	str, err := doRequest(req, r.s.auth)
	if err != nil {
		return nil, err
	}
	return api.Decode([]byte(str))
}

标签:body,调用,return,err,nil,Request,golang,链式,string
From: https://blog.51cto.com/landandan/6372556

相关文章

  • 一次折腾 Golang 泛型、反射和 gorm 框架的记录
    事情的起初是一个很常见的需求:批量更新多条记录的相同字段,每条记录对应的字段值不同因此无法批量Update。看着没啥难度却没想到从开头到结束整整花了一天的时间,遂有此文。首先尝试了gorm自带的Save(),按理说gorm本身会自动识别零值不去更新,这样直接创建一个实例数组挨个赋值......
  • 使用 Java 代码调用 openAI 的 ChatGPT API
    前提:在https://beta.openai.com/account/api-keys注册一个自己的APIkey.要在JavaSpringFramework中使用OpenAIAPI,您需要使用一个能够处理HTTP请求的库。其中一个流行的库是SpringRestTemplate库。RestTemplate是一个强大而灵活的库,可以轻松地发送HTTP请求并处理响应。首......
  • Golang入门笔记
    第一个Go程序packagemain //包,表明代码所在的模块(包)import"fmt" //引入代码依赖//功能实现funcmain(){ fmt.Println("HelloWorld");}编译执行➜go-examplegit:(master)✗cdsrc/example/main➜maingit:(master)✗lshello_world.go➜maingit:......
  • 【2023 · CANN训练营第一季】——Ascend C算子代码分析—Add算子(内核调用符方式)
    前言:AscendC算子(TIKC++)使用C/C++作为前端开发语言,通过四层接口抽象、并行编程范式、孪生调试等技术,极大提高算子开发效率,助力AI开发者低成本完成算子开发和模型调优部署。学习完理论后,上代码,通过实践理解AscendC算子的概念,掌握开发流程,以及内核调用符方式的调试方法。一、算子分......
  • 仅仅是调用第三方接口那么简单吗?
    最近有个项目需要本地处理之后,然后调用第三方接口,本来开始觉得很简单得事情,不就是调用第三方接口吗?但是却一波三折。初版首先有了下面的第一版的设计。这个设计很简单,也是最容易想到的。主要有下面几步1、本地处理;2、调用第三方接口;3、本地日志打印,包括是否调用成功及失败......
  • Mybatis-plus中自定义的sql语句调用QueryWrapper实现查询
     一、引言MP自带的条件构造器虽然很强大,有时候也避免不了写稍微复杂一点业务的sql,那么今天说说MP怎么自定义sql语句吧。 二、具体实现使用注解实现:在我们Mapper接口中定义自定义方法即可。/***@Date:2019/6/1014:40*@Description</span>:User对象持久层*/p......
  • 通过this(...)调用兄弟构造器的作用
    packagecom.Demo1;publicclassTest{publicstaticvoidmain(String[]args){//掌握在类的构造器中,通过this(...)调用兄弟构造器的作用Students1=newStudent("李四",26,"家里蹲大学");//如果学生没有学校,那么学校默认就是黑马程序员......
  • Golang GIN 接收结构体切片(前端对象数组)
    想接收前端这样的数据格式:【json数组】[{"password":"casso","mobile":"13456789999","nick_name":"go","icon":"地址"},{"passwor......
  • Golang环境——GOPATH vs go.mod
    GOPATH在本文中,我们将探讨Go编程的传统环境与基础环境之间的差异go.mod。这种区别对Go开发人员如何构建和管理他们的项目工作区和依赖项具有重要意义。我们将从了解GOPATH环境、它的组织和结构开始。然后,我们将探讨go.mod采用这种方法来提供模块化和灵活的方式来组织Go项......
  • [golang]gin框架接收websocket通信
    前言WebSocket是一种在单个TCP连接上进行全双工通信的协议。WebSocket让客户端和服务端之间的数据交换变得非常简单,且允许服务器主动向客户端推送数据,并且之后客户端和服务端所有的通信都依靠这个专用协议进行。本文使用gin框架编写服务端应用,配置路由接收websocket请求并处理。......