Home Backend Development Golang Go and npm packages: the path of exploration for cross-language development

Go and npm packages: the path of exploration for cross-language development

Apr 08, 2024 pm 02:12 PM
go npm

The cross-language integration of Go and npm packages can be achieved through the cgo tool, which allows Go programs to call C code and then interact with SO files compiled into npm packages, providing Go developers with a way to utilize the functions of npm packages.

Go and npm packages: the path of exploration for cross-language development

Go and npm packages: the path of exploration of cross-language development

In modern software development, cross-language development has become common case. By using the right tools, developers can easily bring together code written in different languages ​​to build flexible and powerful applications. This article will explore cross-language development of Go and npm packages.

Go

Go is an open source, high-performance programming language based on concurrency. Developed by Google, it is known for its readability, security, and high concurrency for building distributed and web applications.

npm

Node.js Package Manager (npm) is an open source package manager for publishing, downloading, and managing JavaScript modules. It makes it easy to integrate third-party libraries and tools into Node.js applications.

Cross-language integration

Cross-language integration of Go and npm packages can be achieved through the cgo tool, which allows Go programs to call C code. By compiling npm packages into shared object (SO) files, Go programs can consume them seamlessly.

Practical Case

Now, let us use a practical case to demonstrate the cross-language integration of Go and npm packages. We will use a Go program to call the bcrypt function in the npm package to encrypt the password.

First, we need to compile the bcrypt npm package:

npm install bcrypt --save
npm run build

This will generate an SO file in node_modules/bcrypt/lib/binding/bcrypt_lib.js.

Now, we can write code in Go to call the bcrypt function:

package main

/*
#cgo CFLAGS: -I/usr/local/include/node
#cgo LDFLAGS: -L/usr/local/lib -lbcrypt
#include <bcrypt.h>
*/
import "C"

func main() {
    password := "password"
    salt := []byte("salty")

    hashedPassword := C.BCrypt(
        C.CString(password),
        C.int(len(salt)),
        (*C.uchar)(&salt[0]),
        C.int(len(salt)),
        C.BCRYPT_VERSION,
    )

    println(C.GoString(hashedPassword))
}

Run

To run this program, execute the following command:

go build main.go
./main

Output

The program will output the encrypted password.

Conclusion

By using the cgo tool, Go developers can easily leverage features in npm packages, making cross-language development tasks easier. Be more simple and efficient. By combining the strengths of different languages, developers can build powerful applications that meet a variety of needs.

The above is the detailed content of Go and npm packages: the path of exploration for cross-language development. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1598
276
How do you work with environment variables in Golang? How do you work with environment variables in Golang? Aug 19, 2025 pm 02:06 PM

Goprovidesbuilt-insupportforhandlingenvironmentvariablesviatheospackage,enablingdeveloperstoread,set,andmanageenvironmentdatasecurelyandefficiently.Toreadavariable,useos.Getenv("KEY"),whichreturnsanemptystringifthekeyisnotset,orcombineos.Lo

How to create and use custom error types in Go How to create and use custom error types in Go Aug 11, 2025 pm 11:08 PM

In Go, creating and using custom error types can improve the expressiveness and debugability of error handling. The answer is to create a custom error by defining a structure that implements the Error() method. For example, ValidationError contains Field and Message fields and returns formatted error information. The error can then be returned in the function, detecting specific error types through type assertions or errors.As to execute different logic. You can also add behavioral methods such as IsCritical to custom errors, which are suitable for scenarios that require structured data, differentiated processing, library export or API integration. In simple cases, errors.New, and predefined errors such as ErrNotFound can be used for comparable

How to implement a generic LRU cache in Go How to implement a generic LRU cache in Go Aug 18, 2025 am 08:31 AM

Use Go generics and container/list to achieve thread-safe LRU cache; 2. The core components include maps, bidirectional linked lists and mutex locks; 3. Get and Add operations ensure concurrency security through locks, with a time complexity of O(1); 4. When the cache is full, the longest unused entry will be automatically eliminated; 5. In the example, the cache with capacity of 3 successfully eliminated the longest unused "b". This implementation fully supports generic, efficient and scalable.

How do you handle signals in a Go application? How do you handle signals in a Go application? Aug 11, 2025 pm 08:01 PM

The correct way to process signals in Go applications is to use the os/signal package to monitor the signal and perform elegant shutdown. 1. Use signal.Notify to send SIGINT, SIGTERM and other signals to the channel; 2. Run the main service in goroutine and block the waiting signal; 3. After receiving the signal, perform elegant shutdown with timeout through context.WithTimeout; 4. Clean up resources such as closing database connections and stopping background goroutine; 5. Use signal.Reset to restore the default signal behavior when necessary to ensure that the program can be reliably terminated in Kubernetes and other environments.

How to use path/filepath for cross-platform path manipulation in Go How to use path/filepath for cross-platform path manipulation in Go Aug 08, 2025 pm 05:29 PM

Usefilepath.Join()tosafelyconstructpathswithcorrectOS-specificseparators.2.Usefilepath.Clean()toremoveredundantelementslike".."and".".3.Usefilepath.Split()toseparatedirectoryandfilecomponents.4.Usefilepath.Dir(),filepath.Base(),an

How do you define and call a function in Go? How do you define and call a function in Go? Aug 14, 2025 pm 06:22 PM

In Go, defining and calling functions use the func keyword and following fixed syntax, first clarify the answer: the function definition must include name, parameter type, return type and function body, and pass in corresponding parameters when calling; 1. Use funcfunctionName(params) returnType{} syntax when defining functions, such as funcadd(a,bint)int{return b}; 2. Support multiple return values, such as funcdivide(a,bfloat64)(float64,bool){}; 3. Calling functions directly uses the function name with brackets to pass parameters, such as result:=add(3,5); 4. Multiple return values can be received by variables or

Performance Comparison: Java vs. Go for Backend Services Performance Comparison: Java vs. Go for Backend Services Aug 14, 2025 pm 03:32 PM

Gotypicallyoffersbetterruntimeperformancewithhigherthroughputandlowerlatency,especiallyforI/O-heavyservices,duetoitslightweightgoroutinesandefficientscheduler,whileJava,thoughslowertostart,canmatchGoinCPU-boundtasksafterJIToptimization.2.Gouseslessme

Parsing RSS and Atom Feeds in a Go Application Parsing RSS and Atom Feeds in a Go Application Aug 18, 2025 am 02:40 AM

Use the gofeed library to easily parse RSS and Atomfeed. First, install the library through gogetgithub.com/mmcdole/gofeed, then create a Parser instance and call the ParseURL or ParseString method to parse remote or local feeds. The library will automatically recognize the format and return a unified feed structure. Then iterate over feed.Items to get standardized fields such as title, link, and publishing time. It is also recommended to set HTTP client timeouts, handle parsing errors, and use cache optimization performance to ultimately achieve simple, efficient and reliable feed resolution.

See all articles