Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to write Go language Library

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how to write a Go language library". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to write a Go language library.

Do not hard-code HTTP clients

Quite right, the library contains the hard coding of http.DefaultClient. While this is not a problem for the library itself, the library's authors do not understand how to use http.DefaultClient. As default client recommends, it is only used if the user does not provide another http.Client. On the contrary, many library authors prefer to hard-code the parts of their code that involve http.DefaultClient, rather than using it as an alternative. This can cause the library to be unavailable in some cases.

First of all, many of us have read the article "Don't use Go's default HTTP client (in production) [1]" about http.DefaultClient 's inability to customize timeouts. When you can't guarantee that your HTTP request will be completed (or at least wait for a completely unpredictable response), your program may encounter strange goroutine leaks and some unpredictable behavior. In my opinion, this makes every library that is hard-coded for http.DefaultClient unavailable.

Second, the network requires some additional configuration. Sometimes you need to use proxies, sometimes you need to rewrite URL, and maybe even http.Transport needs to be replaced by a custom interface. All of this is easy to implement when a programmer uses their own http.Client instance in your library.

The recommended way to handle http.Client in your library is to use the provided client, but if necessary, there is a default alternative:

Func CreateLibrary (client * http.Client) * Library {if client = = nil {client = http.DefaultClient}...}

Or if you want to remove parameters from the factory function, define an helper method in your struct and let the user set its properties as needed:

Type Library struct {Client * http.Client} func (l * Library) getClient () * http.Client {if l.Client = = nil {return http.DefaultClient} return l.Client}

In addition, if some global features are required for each request, people often feel the need to replace http.Client with their own instances. This is the wrong approach-if you need to set some extra headers in your request, or introduce some kind of common feature in your client, you just need to simply set it for each request or replace it completely by assembling a custom client.

Do not introduce global variables

Another negative mode is to allow users to set global variables in a library. For example, allow the user to set a global http.Client in your library and be executed by all HTTP calls:

Var libraryClient * http.Client = http.DefaultClientfunc SetHttpClient (client * http.Client) {libraryClient = client}

Usually there should not be a bunch of global variables in a library. When you write code, you should think about what happens when users use your library multiple times in their programs. Global variables make it impossible for different parameters to be used. Also, introducing global variables into your code can cause testing problems and unnecessary complexity in your code. Using global variables may result in unnecessary dependencies in different modules of your program. It is especially important to avoid the global state when writing your library.

Returns structs instead of interfaces

This is a common problem (in fact, I have made mistakes on this point, too). Many libraries have the following functions:

Func New () LibraryInterface {...}

In the above case, an interface is returned so that the features of struct are hidden in the library. Actually, it should be written like this:

Func New () * LibraryStruct {...}

There should be no declaration of an interface in the library unless it is used in a function parameter. If the above case appears, you should think about your convention when writing this library. When you return an interface, you basically have to declare a series of available methods. If someone wants to use this interface to implement their own functions (for example, for testing), they have to disrupt their code to add more methods. This means that while it is safe to add methods in struct, it is not in interface. If you want to modify some features in the library, you can simply modify some of the public fields in struct. But if your library only provides users with an interface, it won't work.

Use configuration structures to avoid modifying your APIs

Another way to configure is to receive a configuration structure in your factory function instead of passing configuration parameters directly. You can optionally add new parameters without breaking the existing API. All you need to do is add a new field to the Config structure and make sure it doesn't affect its original features.

Func New (config Config) * LibraryStruct {...}

The following is the correct scenario for adding structural fields. If a user forgets to add the field name when initializing the structure, this is a scenario where I think it is forgiven to modify their code. To maintain compatibility, you should use person {name: "Alice", age: 30} instead of person {"Alice", 30} in your code.

You can see the supplement to the above in the golang.org/x/crypto [4] package. In summary, for configuration, I think it is better to allow users to set different parameters in the returned structure, and this specific method is used only when writing complex methods.

Thank you for your reading, the above is the content of "how to write Go language library", after the study of this article, I believe you have a deeper understanding of how to write Go language library, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report